const jwt = require("jsonwebtoken");

// 假设你有一个密钥来验证JWT
const secretKey = "xiaoke";

// 解析JWT的中间件
const jwtMiddleware = (req, res, next) => {
  const token = req.headers["authorization"];
  //登录不检测token
  if (req.path == "/user") {
    next();
    return;
  }
  if (token == null) {
    return res.status(401).send({
      meta: {
        msg: "没有填入token",
        status: 200,
      },
    });
  }
  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) return res.sendStatus(401);
    // 如果JWT有效，则将解码的信息添加到请求对象
    req.decoded = decoded;
    next();
  });
};
module.exports = jwtMiddleware;
